package com.example.utils;

import java.util.Random;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

/**
 * @className: RandomUtils
 * @description: 常用方法，比如批量生成手机号
 * @date: 2021/4/12 下午5:39
 * @author: gqd
 * @version: 1.0
 */
public class RandomUtils {

    /**
     * 随机生成手机号-安全的
     * @return 
     */
    public static String getRanomPhone_new() {
        String phonePrefix = "133";
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
            int num = secureRandom.nextInt(99999999);
            phonePrefix = phonePrefix + num;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
        return phonePrefix;
    }

    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
 
        for (int i = 0; i < length; i++) {
            // 生成一个随机字符（可进一步自定义为只包含特定字符）
            int randomChar = random.nextInt(95) + 32;
 
            // 转换为字符
            if (randomChar >= 58 && randomChar <= 64) {
                // 若生成数字与特殊字符的概率较高，则再次尝试
                i--;
                continue;
            }
            sb.append((char) randomChar);
        }
 
        return sb.toString();
    }
}
